import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DescriptionsType } from '@/components/DescriptionsType';
import { CheckCircleOutlined, SaveOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Space, Button, Modal } from 'antd';
import { OpenAssetModal } from '../mconfig/OpenAssetModal';
import { AssetListManageContext, IAssetListActionEnum, useAssetListManageReducer } from '../mconfig';
import { addStorageService, approvedMaintenanceSerivice, editStorageService, getDetailService } from '../services/UpdateService';
import { getPosIDs, getTenantID, getUserID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { BGflowBusinessType, orderType, requestController } from '../common/Format';
import '../common/style.less';
import moment from 'moment';
import { DetailInfoViewBottomBtn } from '../mconfig/DetailInfoViewBottomBtn';
import { RevokeModal } from '../../Acomponents/RevokeModal';

const UpdataMaterialModal: React.FC<any> = ({ curRes, locationProps }) => {
  /** 引入上下文 */
  const { addAssetList, selectAssetList, assetListDispatch } = useAssetListManageReducer();

  /** 样式根目录 */
  const { prefixCls, assetForm, styleFixCls } = useContext(AssetListManageContext);

  /** 打开选择资产列表 */
  const [openAssetModal, setOpenAssetModal] = useState<boolean>(false);

  /** 详情数据 */
  const [detailInfo, setDetailInfo] = useState<any>({});

  /** 是否提交状态 */
  const [submitState, setSubmitState] = useState<boolean>(false);

  /** 资产维保申请审批同意判断是否可以调用同步接口 */
  const [auditSuccessState, setAuditSuccessState] = useState(false);

  /** 工作流 */
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  /** 处理工作流功能 权限 */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll?.ASSET_MAINTENANCE_STATUS}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`;
    const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [detailInfo]);

  /** 选择材料弹窗 */
  const openAssetModalStatus = () => {
    setOpenAssetModal(true);
  };

  /** 获取表单配置 */
  const { config, methods } = getUpdateConfig({
    pageType: locationProps.state.pageType,
    record: locationProps?.state?.pageType === 'add' ? locationProps?.state?.record : detailInfo,
    openAssetModalStatus,
  });

  /** 获取维保详情回调 */
  const updataGetDetail = (res: any) => {
    if (res && res?.msgFlag) {
      let obj = JSON.parse(JSON.stringify(res?.obj));
      obj.createTime = moment(obj.createTime);
      // obj.handleTime && (obj.handleTime = moment(obj.handleTime));
      // obj.newMaintenTime && (obj.newMaintenTime = moment(obj.newMaintenTime));
      /** 保存新增编辑数据 */
      setDetailInfo(obj);
      assetListDispatch({
        type: IAssetListActionEnum.SELECT_ASSET,
        payload: obj?.massetMaintenDetailList ? obj?.massetMaintenDetailList : [],
      });
      /** 是否是审核中 */
      if (
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.ASSET_MAINTENANCE_STATUS}1001`
      ) {
        setAuditSuccessState(true);
      }

      message.success(res?.msg);
    }
  };

  /** 新增编辑回调 */
  const updateAddCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      if (submitState) {
        let obj = JSON.parse(JSON.stringify(res?.obj));
        obj.createTime = moment(obj.createTime);
        // obj.handleTime = moment(obj.handleTime);
        // obj.newMaintenTime = moment(obj.newMaintenTime);
        /** 保存新增编辑数据 */
        setDetailInfo(obj);
        assetListDispatch({
          type: IAssetListActionEnum.SELECT_ASSET,
          payload: obj?.massetMaintenDetailList ? obj?.massetMaintenDetailList : [],
        });
        /** 打开工作流弹窗 */
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        history.push({
          pathname: '/assetMaintenanceController/manage',
          state: {
            delRouterNameSource: history.location.pathname,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 提交按钮 */
  const handleSubmit = () => {
    if (!submitState) {
      setSubmitState(true);
      handleSave();
    } else {
      /** 打开工作流弹窗 */
      setWorkFlowInfoObj({
        selectFlowRows: detailInfo,
        showWorkFlowModal: true,
        saveNoDefaultFlowID: '',
      });
    }
  };

  /** 工作流通过结束后调用改变状态的接口回调 */
  const approvedMaintenanceCallback = (res: Record<string, any>) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: '/assetMaintenanceController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 提交流程后跳转到管理页面 */
  const reloadManage = () => {
    setSubmitState(false);
    history.push({
      pathname: '/assetMaintenanceController/manage',
      state: {
        delRouterNameSource: history.location.pathname,
      },
    });
  };

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 获取维保详情 */
  const { getDetailLoading, getDetailRun } = getDetailService(updataGetDetail);
  /** 提交维保申请 */
  const { addStorageLoading, addStorageRun } = addStorageService(updateAddCallback);
  /** 编辑维保申请 */
  const { editStorageLoading, editStorageRun } = editStorageService(updateAddCallback);
  /** 工作流通过结束后调用改变状态的接口 */
  const { approvedMaintenanceLoading, approvedMaintenanceRun } = approvedMaintenanceSerivice(approvedMaintenanceCallback);

  // 暂存按钮
  const handleSave = () => {
    config.form.validateFields()?.then((values: any) => {
      values.createTime = moment(values.createTime).format('YYYY-MM-DD HH:mm:ss');
      // values.handleTime = moment(values.handleTime).format('YYYY-MM-DD HH:mm:ss');
      // values.newMaintenTime = moment(values.newMaintenTime).format('YYYY-MM-DD HH:mm:ss');
      if (selectAssetList.length === 0) {
        message.error('请选择资产！');
        return;
      }
      values.massetMaintenDetailList = [...selectAssetList];
      values.createTime = moment(values?.createTime).format('YYYY-MM-DD HH:mm:ss');
      if (locationProps?.state?.pageType === 'add') {
        values.businessType = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1018`;
        addStorageRun(values);
      } else {
        let obj = { ...detailInfo, ...values };
        editStorageRun(obj);
      }
    });
  };

  /** 返回tab子页面 */
  const tabsItem = () => {
    let items: any[] = [
      {
        label: '申请详情',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>
            <div className="tabsBodyBottomBtn">
              <Space>
                {/* {locationProps?.state?.pageType !== 'detail' ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_MAINTENANCE_STATUS}1003` &&
                    detailInfo?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1003`) ? (
                  <Button type={'primary'} icon={<SaveOutlined />} onClick={handleSave}>
                    暂存
                  </Button>
                ) : null} */}
                {((!detailInfo?.state ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_MAINTENANCE_STATUS}1000` && !detailInfo?.checkState) ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_MAINTENANCE_STATUS}1003` &&
                    detailInfo?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1003`)) &&
                detailInfo?.createrID == getUserID() )|| locationProps?.state?.pageType === 'add'? (
                  <Button type={'primary'} onClick={handleSubmit}>
                    提交
                  </Button>
                ) : null}
                <Button danger onClick={closeCurrent}>
                  关闭
                </Button>
              </Space>
            </div>
            {/* <div className="tabsBodyBottomBtn">
              <Space>
                {locationProps?.state?.pageType == 'detail' ? (
                  <WorkflowHndTaskBtn
                    flowDetailInfo={detailInfo}
                    reloadCallback={() => {
                      getDetailRun(detailInfo?.id);
                    }}
                    requestController={'assetMainten'}
                    flowBusinessType={BGflowBusinessType()}
                  />
                ) : null}
              </Space>
            </div> */}
          </div>
        ),
      },
    ];
    return items;
  };

  /** 监听审核状态 */
  useEffect(() => {
    if (
      auditSuccessState &&
      detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
      detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.ASSET_MAINTENANCE_STATUS}1002`
    ) {
      detailInfo.createTime = moment(detailInfo.createTime).format('YYYY-MM-DD HH:mm:ss');
      approvedMaintenanceRun({ ...detailInfo, workflowResult: true });
    }
  }, [detailInfo?.checkState, detailInfo?.state]);

  useEffect(() => {
    if (locationProps?.state?.pageType != 'add') {
      getDetailRun(locationProps?.state?.record?.id);
    }
  }, []);

  /** 申请页ref */
  const { confirm } = Modal;

  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  const changeRevoke = () => {
    setInvalidState({
      isShow: true,
      resObj: detailInfo,
    });
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    return (
      <DetailInfoViewBottomBtn
        position="top"
        changeRevoke={changeRevoke}
        detailInfo={detailInfo}
        getDetailRun={getDetailRun}
        locationProps={locationProps}
        handleSave={handleSave}
        handleSubmit={handleSubmit}
      />
    );
  };

  return (
    <>
      <AssetListManageContext.Provider
        value={{
          prefixCls,
          styleFixCls,
          curRes,
          addAssetList,
          selectAssetList,
          assetForm,
          assetListDispatch,
        }}
      >
        <div className={'apply-update-UpdataIntentBox'}>
          <Spin spinning={addStorageLoading || getDetailLoading || editStorageLoading || approvedMaintenanceLoading}>
            <Row className={`${styleFixCls}row`}>
              <Col span={24} className={`${styleFixCls}row-col`}>
                <Tabs
                  className={pageStyles['commonTabs']}
                  type="card"
                  onChange={(activeKey: string) => {}}
                  items={tabsItem()}
                  destroyInactiveTabPane={true}
                  tabBarExtraContent={contactsTabsExtra()}
                />
              </Col>
            </Row>

            {/* 选择材料列表 */}
            {openAssetModal && (
              <OpenAssetModal
                curRes={curRes}
                isShowModal={openAssetModal}
                onClose={() => {
                  setOpenAssetModal(false);
                }}
              />
            )}

            {/* 撤销弹窗 */}
            {invalidState?.isShow && (
              <RevokeModal
                resObj={invalidState?.resObj}
                revokeRequestUrl={'/assetMainten/revoke'}
                onClose={() => setInvalidState({})}
                reqBody={{ id: invalidState?.resObj?.id, state: `${getTenantID()}${ILoadMapTypeAll?.ASSET_MAINTENANCE_STATUS}1000` }}
                modalTip={
                  <div style={{ color: '#000' }}>
                    确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
                  </div>
                }
                reloadRequest={() => {
                  history.push({
                    pathname: locationProps?.state?.returnPathName,
                    state: {
                      delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                      returnPathName: locationProps?.state?.returnPathName,
                    },
                  });
                }}
              />
            )}

            {/* 工作流-----审批记录 */}
            {detailInfo?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1018`] && (
              <WorkflowChedkRecord
                curRes={curRes}
                dataDetailInfo={detailInfo}
                flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1018`}
                requestController={requestController()}
                reloadPageCallback={() => {
                  getDetailRun({ id: detailInfo?.id });
                }} // 刷新方法-详情方法
                revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.ASSET_MAINTENANCE_STATUS}1000`}
                allBtnFuncQuqry={workflowPowerAllBtn}
                tabPaneHeight={0.35}
                isCheckDrawer={true}
                isShowCollapse={isShowWorkRecord}
                changeCollapse={(val) => {
                  setIsShowWorkRecord(val);
                }}
                cancelStateId={`${getTenantID()}${ILoadMapTypeAll?.ASSET_MAINTENANCE_STATUS}1004`}
                isSyncArchive={true}
              />
            )}

            {/* 工作流-----发起流程审批弹窗 */}
            {workFlowInfoObj?.showWorkFlowModal && (
              <WorkflowSwitchModal
                openVisible={workFlowInfoObj?.showWorkFlowModal}
                businessInfoObj={workFlowInfoObj?.selectFlowRows}
                requestController={requestController()}
                orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
                category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1018`}
                // businessCategory={`${getTenantID()}${ILoadMapTypeAll.INTENTION_CATEGORY}1000`}
                businessCategory={``}
                selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
                reloadInfoCallback={() => {
                  reloadManage();
                }}
                openFlowChangeModal={setShowSwitchFlow}
                onClose={() => {
                  setWorkFlowInfoObj({
                    ...workFlowInfoObj,
                    showWorkFlowModal: false,
                  });
                  history.push({
                    pathname: '/assetMaintenanceController/manage',
                    state: {
                      delRouterNameSource: history.location.pathname,
                    },
                  });
                }}
                replaceStrObj={{ own: 'own', workflowType: 'category' }}
              />
            )}

            {/* 挑选流程组件 */}
            {showSwitchFlow && (
              <WorkflowNoDefaultTable
                openVisibleSwitch={showSwitchFlow}
                onCloseSwitch={closeSwitchFlowModal}
                requestController={'assetMainten'}
                orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
                category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1018`}
                businessCategory={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1018`}
                saveSelectFlowID={(flowId: string) => {
                  setWorkFlowInfoObj({
                    ...workFlowInfoObj,
                    saveNoDefaultFlowID: flowId,
                  });
                }}
                selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
              />
            )}
          </Spin>
        </div>
      </AssetListManageContext.Provider>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdataMaterialModal);
